local skynet = require "skynet"
local cluster = require "skynet.cluster"
local socket = require "skynet.socket"
local httpd = require "http.httpd"
local sockethelper = require "http.sockethelper"
local urllib = require "http.url"
local table = table
local string = string

local filelog = require "filelog"
local timetool = require "timetool"
local md5 = require "md5"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

--所有真人游戏
local all_zrgames = {"zrbjl", "zrlhd"}

local function response(id, ...)
	local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
	if not ok then
		-- if err == sockethelper.socket_error , that means socket closed.
		skynet.error(string.format("fd = %d, %s", id, err))
	end
end

--处理数据
local function handle_data(data)
	local srcdata = json.decode(data) or {}
	local tablekey = srcdata.tablekey or "nil"
	if srcdata.gamename == "bjl" then
		skynet.pcall(cluster.send, "zrbjlnode", ".router", "update_gamedata", tablekey, srcdata.gamedata)
	elseif srcdata.gamename == "lhd" then
		skynet.pcall(cluster.send, "zrlhdnode", ".router", "update_gamedata", tablekey, srcdata.gamedata)
	elseif srcdata.gamename == "brnn" then
		skynet.pcall(cluster.send, "zrbrnnnode", ".router", "update_gamedata", tablekey, srcdata.gamedata)
	elseif srcdata.gamename == "all" then
		for _,gamename in pairs(all_zrgames) do
			skynet.pcall(cluster.send, gamename .. "node", ".router", "update_gamedata", "all", srcdata.gamedata)
		end
	end
end

----------------------------------

skynet.start(function()
	skynet.dispatch("lua", function (_,_,id)
		socket.start(id)
		-- limit request body size to 8192 (you can pass nil to unlimit)
		local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), nil)
		if code then
			if code ~= 200 then
				response(id, code)
			else
				local tmp = {}
				local path, query = urllib.parse(url)
				local action = string.sub(path,2) --去掉 / 
				if action == "gamedata" and body then
					handle_data(body)
				end
				response(id, code, json.encode(tmp))
			end
		else
			if url == sockethelper.socket_error then
				skynet.error("socket closed")
			else
				skynet.error(url)
			end
		end
		socket.close(id)
	end)
end)
